package DataOperator;

import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.util.ArrayList;



public class SoundPackager {

	static final String mainDir = "../voice/";
	static final String backDir = "../sound/";
	static final String multDir = "../multi/";
	static final String pacFileName = "Out\\Sound";
	
	DataOutputStream pacFile = null;
	OutputStreamWriter logFile = null;
	int offset = 0;
	ArrayList<Integer> pacInfo = new ArrayList<Integer>();
	
	public void Init(){
		try{
			pacFile = new DataOutputStream(new FileOutputStream(pacFileName));
		}
		catch(IOException e){
			e.printStackTrace();
		}
	}
	
	public boolean PackWordSound(String word, WordBuildInfo wordInfo){
		int numSound = wordInfo.GetSoundNum();
		//assert(numSound <= 2);
		char key = word.charAt(0);
		if(key < 'A' || key > 'z'){
			return false;
		}
		pacInfo.clear();
		String filePath = mainDir + key + "/" + word + ".wav";
		File file = new File(filePath);
		if(!file.exists()){
			filePath = backDir + key + "/" + word + ".mp3";
			file = new File(filePath);
			if(!file.exists()){
				return false;
			}
		}
		pacInfo.add(offset);
		PackFile(file);
		if(numSound == 2){
			filePath = multDir + word + ".mp3";
			file = new File(filePath);
			if(file.exists()){
				PackFile(file);
			}
			else{
				System.out.println("Unable find 2nd " + word + " file in mult dir");
			}
		}
		wordInfo.SetSoundInfo(pacInfo);
		return !pacInfo.isEmpty();
	}
	
	private void PackFile(File file) {
		int length = (int)file.length();
		byte[] buffer = new byte[length];
		try {
			FileInputStream data = new FileInputStream(file);
			data.read(buffer);
			pacFile.write(buffer);
		} catch (IOException e) {
			e.printStackTrace();
		}
		pacInfo.add(length);
		offset += length;
	}
}
